import request from './request/request.js'
class WXKeyManager {

	getWXKey() {
		let promise = new Promise((resolve, reject) => {
			uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					console.log(loginRes)
					request.post({
							url: 'user/setWXCode',
							data: {
								code: loginRes.code
							}
						})
						.then(response => {
							const data = response.data;
							resolve(data)
							console.log('wxkey------', data);
						});
				},
				fail: err => {
					// console.log('err',err);
					reject(err)
				}
			});

		})
		return promise;
	}
	getWXKeyWithCode(code){
		let promise = new Promise((resolve, reject) => {
			request.post({
					url: 'user/setWXCode',
					data: {
						code: code
					}
				})
				.then(response => {
					const data = response.data;
					resolve(data)
					console.log('wxkey------', data);
				});
		})
		return promise;
	}
	decryptPhoneNumberWithCode(e,code){
		console.log("点击获取手机号码按钮xxxxxxxx");
		console.log("code--xxxxxxxx"+code);
		//点击获取手机号码按钮
		let promise = new Promise((resolve, reject) => {
			let encrypdata = e.detail.encryptedData;
			let ivdata = e.detail.iv;
			if (encrypdata && ivdata) {
				this.getWXKeyWithCode(code).then(res => {
					this.phoneNumberRequest(encrypdata, ivdata, res.session_key, res.openid).then(res => {
						resolve(res)
					})
				})
			} else {
				reject({
					"msg": "未知错误"
				})
			}
		
		})
		return promise
	}
	decryptPhoneNumber(e) {
		console.log("点击获取手机号码按钮xxxxxxxx");
		//点击获取手机号码按钮
		let promise = new Promise((resolve, reject) => {
			let encrypdata = e.detail.encryptedData;
			let ivdata = e.detail.iv;
			if (encrypdata && ivdata) {
				console.log("1111111xxxxxxxx");
				this.getWXKey().then(res => {
					console.log("2222222222xxxxxxxx");
					this.phoneNumberRequest(encrypdata, ivdata, res.session_key, res.openid).then(res => {
						resolve(res)
					})
				})
			} else {
				reject({
					"msg": "未知错误"
				})
			}

		})
		return promise
	}
	phoneNumberRequest(encrypdata, ivdata, sessionKey, openid) {
		console.log("encrypdata------", encrypdata);
		console.log("ivdata------", ivdata);
		console.log("sessionKey------", sessionKey);
		console.log("openid------", openid);
		let promise = new Promise((resolve, reject) => {
			request
				.post({
					url: 'user/wxlogin',
					data: {
						encryptedData: encrypdata,
						iv: ivdata,
						sessionKey: sessionKey,
						openid: openid
					}
				})
				.then(res => {
					const data = res.data;
					uni.setStorageSync('userInfo', data);
					getApp().globalData.userInfo = data;
					resolve(data)
					try {
						uni.setStorageSync('token', data.token);
					} catch (e) {
						reject(e)
					}
				});
		})
		return promise;
	}

}
var wxKeyManager = new WXKeyManager()
/**
 * @module {Request} request
 */
export default wxKeyManager
